
<?php

    /**
     * 翻页函数封装
     * $parem link      数据库连接
     * $parem table     表名
     * $parem cur_page  当前页
     * $parem per_page  每页显示记录数
     * $parem page_num  固定页码数
     * @return string
     * @author myy
     **/

  function getPages($link,$table,$cur_page,$where=1,$per_page=5,$page_num=5){


    // 翻页功能


    //求数据表页码的总记录数

     $sql = "select count(*) as total from `$table`  where $where  "; //  15



    $result = mysqli_query($link,$sql);


     $total_num = mysqli_fetch_assoc($result)['total'];

    //求总页码数 并向上取整
      $total_page = ceil($total_num/$per_page);

    //求访问a标签页码的前后偏移幅(页码偏移幅)  公式：向下取整（固定页码数/2）
    $offset_page = floor($page_num/2);

    // 计算循环的起始值  固定页码-页码偏移幅
    $start = $cur_page-$offset_page;
    // 计算循环的结束值  固定页码+页码偏移幅
    $end =  $cur_page+$offset_page;

    if($total_num<$page_num){
      $start=1;
      $end=$total_num;
    }
  //优化一：页数出现小于1的情况
    //判断是否出现小于1的数
    if($start<1){
      $start=1;
      $end=$page_num;
    }
  //优化二：页数出现大于总页码数的情况
    //判断是否出现大于总页码数的数
    if($end>$total_page){
      $start=($total_page-$page_num+1)<=0?1:$total_page-$page_num+1;
      $end=$total_page;
    }

    $pages = '';

    //首页
    $disabled = $cur_page==1?'disabled':'';
    $href = $cur_page==1?'javascript:void(0)':'index.php?c='.$GLOBALS['c'].'&a='.$GLOBALS['a'].'&admin=1&p=1';
    $pages.='<li class="'.$disabled.'"><a href="'.$href.'">首页</a></li>';

    //上一页
    $disabled = $cur_page==1?'disabled':'';
    $prev_page = $cur_page-1;
    $prev_href = $cur_page==1?'javascript:void(0)':'index.php?c='.$GLOBALS['c'].'&a='.$GLOBALS['a'].'&admin=1&p='.$prev_page;
    $pages.='<li class="'.$disabled.'"><a href="'.$prev_href.'">上一页</a></li>';

    // 动态生成中间5页页码
    for($i=$start;$i<=$end;$i++){
      // <!-- 判断当前页码是否等于$i的值  是则显示选中状态的li标签 -->
      if($i==$cur_page){
        $pages .= '<li class="active"><a href="javascript:void(0)">'.$i.'</a></li>';
      }else{
        $pages .= '<li><a href="index.php?c='.$GLOBALS['c'].'&a='.$GLOBALS['a'].'&admin=1&p='.$i.'">'.$i.'</a></li>';
      }
    }

    //下一页
    $disabled = $cur_page==$total_page?'disabled':'';
    $next_page = $cur_page+1;
    $next_href = $cur_page==$total_page?'javascript:void(0)':'index.php?c='.$GLOBALS['c'].'&a='.$GLOBALS['a'].'&admin=1&p='.$next_page;
    $pages.='<li class="'.$disabled.'"><a href="'.$next_href.'">下一页</a></li>';

    //尾页
    $disabled = $cur_page==$total_page?'disabled':'';
    $last_href = $cur_page==$total_page?'javascript:void(0)':'index.php?c='.$GLOBALS['c'].'&a='.$GLOBALS['a'].'&admin=1&p='.$total_page;
    $pages.='<li class="'.$disabled.'"><a href="'.$last_href.'">最后一页</a></li>';


    return $pages;
  }